import indexedDB from "./index";

interface HistoryRecord {
  articleId: string; // 文章唯一标识
  timestamp: number; // 访问时间戳
  metaData?: {
    // 扩展元数据
    scrollPosition?: number; // 阅读进度
    duration?: number; // 阅读时长（秒）
  };
}

const addHistory = async (data: HistoryRecord) => {
  return indexedDB.updateData("history", data, "add");
};

const getHistoryByArticle = async (articleId: string) => {
  console.log(
    "获取历史记录",
    articleId,
    indexedDB.db!.transaction("history").objectStore("history")
  );
  const index = indexedDB
    .db!.transaction("history")
    .objectStore("history")
    .index("articleId");
  return new Promise((resolve, reject) => {
    const request = index.getAll(articleId);
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
};

export const getArticleHistory = async (articleId: string) => {
  const all = (await indexedDB.getData("history")) as HistoryRecord[];
  return all
    .filter((r) => r.articleId === articleId)
    .sort((a, b) => b.timestamp - a.timestamp);
};

export const MAX_HISTORY = 100;

// 保存历史记录
export const saveHistory = async (articleId: string, content: string) => {
  const record = {
    articleId,
    content,
    timestamp: Date.now(),
  };

  await indexedDB.updateData("history", record, "add");
  await clearOldHistory(articleId);
};

// 清理旧历史记录
const clearOldHistory = async (articleId: string) => {
  const history = await getArticleHistory(articleId);
  if (history.length > MAX_HISTORY) {
    const toDelete = history.slice(MAX_HISTORY);
    await Promise.all(
      toDelete.map((record) =>
        indexedDB.deleteData("history", record.articleId)
      )
    );
  }
};

// 删除文章所有历史记录
export const deleteArticleHistory = async (articleId: string) => {
  await indexedDB.deleteAllDataByKey("history", "articleId", articleId);
};

export default {
  addHistory,
  getHistoryByArticle,
  clearOldHistory,
  getArticleHistory,
  saveHistory,
  deleteArticleHistory,
};
